package cn.iocoder.yudao.module.call.controller.open.ivrinput;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.call.controller.admin.ivrinput.vo.IvrInputSaveReqVO;
import cn.iocoder.yudao.module.call.controller.open.ivrinput.vo.IvrInputSaveByFlowReqVO;
import cn.iocoder.yudao.module.call.dal.dataobject.ivrflow.IvrFlowDO;
import cn.iocoder.yudao.module.call.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.call.service.ivrflow.IvrFlowService;
import cn.iocoder.yudao.module.call.service.ivrinput.IvrInputService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

import java.util.Objects;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "open - ivr用户输入")
@RestController
@RequestMapping("/call/lua/ivr-input")
@Validated
@Slf4j
public class IvrInputLuaController {

    @Resource
    private IvrInputService ivrInputService;

    @Resource
    private IvrFlowService ivrFlowService;

    @PostMapping("/create")
    @Operation(summary = "保存用户输入")
    @OperateLog(enable = false)
    @TenantIgnore
    public CommonResult<Long> create(@Valid @RequestBody IvrInputSaveByFlowReqVO IvrInputSaveByFlowReqVO) {
        IvrFlowDO ivrFlowDO = ivrFlowService.getIvrFlowById(IvrInputSaveByFlowReqVO.getFlowId());
        if (Objects.isNull(ivrFlowDO)) {
            return error(ErrorCodeConstants.IVR_FLOW_NOT_EXISTS);
        }
        IvrInputSaveReqVO ivrInputSaveReqVO = new IvrInputSaveReqVO();
        ivrInputSaveReqVO.setCallId(IvrInputSaveByFlowReqVO.getCallId());
        ivrInputSaveReqVO.setGroupId(ivrFlowDO.getGroupId());
        ivrInputSaveReqVO.setFlowId(ivrFlowDO.getId());
        ivrInputSaveReqVO.setNodeId(IvrInputSaveByFlowReqVO.getNodeId());
        ivrInputSaveReqVO.setContent(IvrInputSaveByFlowReqVO.getContent());
        ivrInputSaveReqVO.setNodeName(IvrInputSaveByFlowReqVO.getNodeName());
        return success(TenantUtils.execute(ivrFlowDO.getTenantId(), () -> ivrInputService.createIvrInput(ivrInputSaveReqVO)));
    }

}
